<template>
  <el-dialog
    :title="'影像材料备案'"
        :fullscreen="true"
    top="0"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="150px">

      <el-row>
        <el-col :span="12">
              <el-form-item label="备案类型" prop="ftype">
                <el-select v-model="dataForm.ftype" @change="ftypeChange" placeholder="备案类型" style="width:100%">
                    <el-option
                      v-for="item in ftypeList"
                      :key="item.value"
                      :label="item.text"
                      :value="item.value">
                    </el-option>
                </el-select>
              </el-form-item>
        </el-col>
        <el-col :span="12">
              <el-form-item label="地市" prop="seRegion" v-if="true">
                <el-select  @change="selectChanged" v-model="dataForm.seRegion" placeholder="地市" style="width:100%">
                    <el-option
                      v-for="item in dataForm.seRegionList"
                      :key="item.code"
                      :label="item.name"
                      :value="item.code">
                    </el-option>
                </el-select>
              </el-form-item>
        </el-col>
      </el-row>
    <el-form-item label="登记中心" prop="djzx"    v-if="false"  >
      <el-select v-model="dataForm.djzx" placeholder="登记中心" style="width:100%">
          <el-option
            v-for="item in dataForm.bankList"
            :key="item.bankid"
            :label="item.bankname"
            :value="item.bankid">
          </el-option>
      </el-select>
    </el-form-item>

    <el-row  v-if="dataForm.ftype == '02' || dataForm.ftype == '09' || dataForm.ftype == '03' || dataForm.ftype == '04'">
      <el-col :span="12">
        
     <el-form-item label="区县" prop="region"  v-if="dataForm.ftype == '02' || dataForm.ftype == '09'">
      <el-select v-model="dataForm.region" placeholder="区县" style="width:100%">
          <el-option
            v-for="item in dataForm.regionList"
            :key="item.code"
            :label="item.name"
            :value="item.code">
          </el-option>
      </el-select>
    </el-form-item>
      </el-col>
      <el-col :span="12" v-if="dataForm.ftype == '02' || dataForm.ftype == '03' || dataForm.ftype == '04'">
            <el-form-item label="经办人员姓名" prop="name">
                  <el-input v-model="dataForm.name" placeholder="经办人员姓名"></el-input>
            </el-form-item>
      </el-col>
    </el-row>

    <el-row  v-if="dataForm.ftype == '02' || dataForm.ftype == '03' || dataForm.ftype == '04'">
      <el-col :span="12">
        <el-form-item label="经办人员证件号码" prop="idcode">
                  <el-input v-model="dataForm.idcode" placeholder="经办人员证件号码"></el-input>
            </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="经办人员手机号码" prop="phone">
                  <el-input v-model="dataForm.phone"  placeholder="经办人员手机号码"></el-input>
            </el-form-item>
      </el-col>
    </el-row>


    <el-row>
      <el-col :span="12">
        <el-form-item label="有效开始时间" prop="enabledate" >
          <el-date-picker v-model="dataForm.enabledate" placeholder="开始日期"  format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width:100%" ></el-date-picker> 
      </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="有效结束时间" prop="disabledate" >
            <el-date-picker v-model="dataForm.disabledate" placeholder="结束日期"  format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width:100%" ></el-date-picker>      
        </el-form-item>
      </el-col>
    </el-row>
    
    
    <el-row>

      <el-col :span="12">
            <el-form-item label="备注说明" prop="comment">
                <el-input v-model="dataForm.comment" type="textarea" placeholder="备注说明"></el-input>
          </el-form-item>
      </el-col>

            <el-col :span="12" v-if="dataForm.ftype != '05'">
        <el-form-item label="抵押权人"  prop="orgid" >

          <el-select
                v-model="dataForm.orgid"
                clearable

                filterable
                style="width:100%"
                remote
                placeholder="输入抵押权人代码或名称"
                :remote-method="remoteMethod"
                :loading="loading">
                <el-option
                  v-for="item in list"
                  :key="item.branchid"
                  :label="item.branchname"
                  :value="item.branchid">
                </el-option>
              </el-select>

        </el-form-item>
      </el-col>
    </el-row>




    <el-form-item label="上传影像">
      <el-upload :action="url" 
                        multiple
                        ref="upload"       
                              
                        :on-success="successHandle"
                        :on-error="errorHandle"
                        :file-list="fileList"
                        :show-file-list="true"
                        :on-exceed="handleExceed"
                        :data="{yxbabsm:this.yxbabsm, ftype:this.dataForm.ftype, seRegion:this.dataForm.seRegion, djzx:this.dataForm.djzx}"
                        :before-remove="beforeRemove"
                        :on-remove="removeFile"
                        :limit="limit"
                        accept="image/jpg"
                        :before-upload="beforeUploadHandle"
                      
                                            >
                                              <el-button size="small" type="primary">点击上传</el-button>
                                            </el-upload>
    </el-form-item>

    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>

  import { isMobile } from '@/utils/validate'

  export default {
    data () {

        var validateComment = (rule, value, callback) => {
        if (value == '影像材料备案注销') {
          callback(new Error('影像材料备案的备注不可以填写【影像材料备案注销】'))
        } else {
          callback()
        }
      }

      var validateIdCard = (rule, value, callback) => {
        if (!this.dataForm.id && !this.datepicker.checkIdNumberValid(value)) {
          callback(new Error('经办人员人证件号码有误'))
        } else {
          callback()
        }
      }

       var validatePhone = (rule, value, callback) => {
        if (!isMobile(value)) {
          callback(new Error('经办人员手机号码有误'))
        } else {
          callback()
        }
      }

      return {
        visible: false,
        yxbabsm: '',
        check: true,
        loading: false,
        url: '',
        limit:1,
        fileList: [],
        ftypeList:[],
        list: [],

        dataForm: {
          seqno: 0,
          region: '',
          name: '',
          idcode: '',
          phone: '',
          seRegion: '',
          enabledate: '',
          disabledate: '',
          regionList: [],
          comment: '',
          seRegionList: [],
          djzx: '',
          bankList: [],
          ftype: '',
          orgid: ''
        },
        dataRule: {
          seRegion: [
            { required: true, message: '地市不能为空', trigger: 'blur' }
          ],
          region: [
            { required: true, message: '区县不能为空', trigger: 'blur' }
          ],
          name: [
            { required: true, message: '经办人员姓名不能为空', trigger: 'blur' }
          ],
           idcode: [
            { required: true, message: '经办人员证件号码不能为空', trigger: 'blur' },
            {validator: validateIdCard, trigger: 'blur'}
          ],
           phone: [
            { required: true, message: '经办人员手机号码不能为空', trigger: 'blur' },
            {validator: validatePhone, trigger: 'blur'}
          ],

          comment: [
            { required: true, message: '备注说明不能为空', trigger: 'blur' },
            { validator: validateComment, trigger: 'blur' }
          ],
          enabledate: [
            { required: true, message: '有效开始时间不能为空', trigger: 'blur' }
          ],
          disabledate: [
             { required: true, message: '有效结束时间不能为空', trigger: 'blur' }
          ]
          ,
          orgid: [
             { required: true, message: '抵押权人不能为空', trigger: 'blur' }
          ]
          ,
          ftype: [
             { required: true, message: '备案类型不能为空', trigger: 'blur' }
          ]
          // ,
          // djzx: [
          //    { required: true, message: '登记中心不能为空', trigger: 'blur' }
          // ]


        }
      }
    },
    methods: {
      init (id) {
        this.dataForm.seqno = id || 0
        this.dataForm.ftype = ''
        this.limit = 1
        this.yxbabsm = ''
        this.visible = true
        this.dataForm.djzx = ''
        this.url = this.$http.adornUrl(`/bdc/bdcrecordimage/upload?token=${this.$cookie.get('token')}`)
        this.fileList = [];
        this.remoteMethod()
        this.$http({
          url: this.$http.adornUrl(`/bdc/bdcrecordimage/item/list`),
              method: 'get',
              params: this.$http.adornParams()
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.yxbabsm = data.yxbabsm
              this.dataForm.seRegionList = data.regionList
              this.dataForm.bankList = data.bankList
              this.ftypeList = data.ftypeList
            }
        })

        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
                   
          if (this.dataForm.seqno) {
            this.$http({
              url: this.$http.adornUrl(`/bdc/bdcrecordimage/info/${this.dataForm.seqno}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {

                this.dataForm.region = data.bdcrecordimage.region
                this.dataForm.seRegion = data.bdcrecordimage.seRegion
                this.dataForm.djzx = data.bdcrecordimage.bdcno
 
   
                this.dataForm.enabledate = data.bdcrecordimage.enabledate
                this.dataForm.disabledate = data.bdcrecordimage.disabledate
                this.dataForm.proxyno = data.bdcrecordimage.proxyno
                this.dataForm.seRegion = data.seRegion
                if (data.filename){
                   this.fileList.push({'name': data.filename})
                }            

              }
            })
          }
        })
      },

      remoteMethod(query) {

          this.loading = true;

          this.$http({
            url: this.$http.adornUrl(`/sys/user/branch/search`),
            method: 'get',
            params: this.$http.adornParams({
              "key": query || ''
            })
          }).then(({data}) => {
            this.loading = false;
            if (data && data.code === 0) {
                this.list = data.list;
            }
          })     
          

      },

      ftypeChange(value){
        if (value == '02' || value == '01' || value == '03' || value == '04'){
          this.limit = 1
        }
        else{
          this.limit = 9999
        }
        this.$refs.upload.clearFiles()   
      },

      removeFile(file, fileList){
          this.$http({
          url: this.$http.adornUrl(`/bdc/bdcrecordimage/remove`),
              method: 'post',
              data: this.$http.adornData({
                'yxbabsm': this.yxbabsm,
                'filename': file.name
              })
          }).then(({data}) => {
            if (data && data.code === 0) {
                              if (this.check){
               this.$message({
                  message: '删除成功',
                  type: 'success',
                  duration: 1500
                })
                              }
 
            }else{
              this.fileList = fileList
            }
        })
      },

      selectChanged(value){
          this.dataForm.region = '';
          this.$http({
          url: this.$http.adornUrl(`/sys/bdcregion/listByLevle`),
              method: 'get',
              params: this.$http.adornParams({'upregion':value})
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.dataForm.regionList = data.list
            }
        })
      },

      errorHandle(err, file, fileList){
        this.removeCurrentFile(file, fileList)
      },

      removeCurrentFile(file, fileList){
        for (var i in fileList){
          if (fileList[i].uid == file.uid){
            fileList.splice(i, 1)
          }
        }
         this.fileList = fileList
      },

      // 上传成功
      successHandle (response, file, fileList) {

        if (response && response.code === 0) {
            this.$message({
              message: '上传文件成功',
              type: 'success',
              duration: 1500
            });
            if (!this.yxbabsm){
              this.yxbabsm = response.yxbabsm
              this.dataForm.djzx = response.djzx
            }
            this.fileList = fileList
        } else {        
          // this.$message.error(response.msg)
          this.$message({
                  message: response.msg,
                  type: 'error',
                  duration: 1500,
                  onClose: () => {
                      this.removeCurrentFile(file, fileList)
                  }
                })          
        }
      },

      // 上传之前
      beforeUploadHandle (file) {
        if (this.dataForm.ftype == ''){
          this.check = false
          this.$message.error("请选择备案类型")
          
          return false
        }

        if (this.dataForm.seRegion == ''){
          this.check = false
          this.$message.error("请选择地市")
          
          return false
        }

        if (file.type !== 'image/jpg' && file.type !== 'image/jpeg') {
            this.check = false
            this.$message.error('只支持jpg格式的图片！')
            return false
        }

        var name = file.name
        if (this.dataForm.ftype == '01' && !name.startsWith("营业执照-")){
          this.check = false
          this.$message.error('文件名格式不对，请参考【营业执照-抵押权人全称.jpg】')
          return false
        }
        else if (this.dataForm.ftype == '02' && !name.startsWith("介绍信-")){
          this.check = false
          this.$message.error('文件名格式不对，请参考【介绍信-温江区-张三510107199010120932.jpg】')
          return false
        }else if (this.dataForm.ftype == '03' && !name.startsWith("身份证-")){
          this.check = false
          this.$message.error('文件名格式不对，请参考【身份证-张三510107199010120932.jpg】')
          return false
        }else if (this.dataForm.ftype == '04' && !name.startsWith("手写签名-")){
          this.check = false
          this.$message.error('文件名格式不对，请参考【手写签名-张三510107199010120932.jpg】')
          return false
        }else if (this.dataForm.ftype == '05' && name.indexOf("-") <= 0){
          this.check = false
          this.$message.error('文件名格式不对，请参考【XX合同-页码.jpg】')
          return false
        }

        if (this.dataForm.ftype == '04'){
          if (file.size > 1024 * 30){
            this.check = false
            this.$message.error('签名图片大小不能超过30K')
            return false
          }




        }

        this.check = true
        return true;
      },

      handleExceed(files, fileList) {
        this.$message.error('备案文件数不能超过'+ this.limit + "个")
      },
      beforeRemove(file, fileList) {
          if (this.check){
           return this.$confirm(`确定移除 ${ file.name }？`);
          }
          
       
        
      },



      // 表单提交
      dataFormSubmit () {

        if (this.$refs.upload.uploadFiles.length == 0){
            this.$message.error("请上传文件")
            return;
        }

        var self = this;
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {

            this.$http({
              url: this.$http.adornUrl(`/bdc/bdcrecordimage/send`),
              method: 'post',
              data: this.$http.adornData({

                // 'djzx': this.dataForm.djzx,
                'ftype': this.dataForm.ftype,
                'comment': this.dataForm.comment,
                'yxbabsm': this.yxbabsm,
                'enabledate': this.dataForm.enabledate,
                'disabledate': this.dataForm.disabledate,
                'orgid': this.dataForm.orgid,
                'seRegion': this.dataForm.seRegion,
                'region': this.dataForm.region,
                'name': this.dataForm.name,
                'idcode': this.dataForm.idcode,
                'phone': this.dataForm.phone,

              })
            }).then(({data}) => {
              if (data && data.code === 0) {

                  this.$message({
                    message: '影像材料备案成功',
                    type: 'success',
                    duration: 1500,
                    onClose: () => {
                      this.visible = false
                      this.$emit('refreshDataList')
                    }
                  })
                
              } else {
                this.$message.error(data.msg)
                var fileKey = data.fileKey
                if (fileKey){
                  console.log(self.fileList.length)
                  console.log(self.yxbabsm)
                  for (var i in this.fileList){
                    if (this.yxbabsm + "_" + this.fileList[i].name == fileKey){
                      this.fileList.splice(i, 1)
                    }
                  }
                }
              }
            })
          }
        })
      }
    }
  }
</script>
